package com.prp.bo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;

import org.hibernate.Transaction;

import com.prp.db.DAOFactory;
import com.prp.db.HibernateSessionFactory;
import com.prp.db.idao.IMsgboardDAO;
import com.prp.db.po.Msgboard;

public class MessageBoardBO {

	/**
	 * 用户添加留言
	 * 
	 * @param content
	 * @param fromUserId
	 * @param toUserId
	 * @return null if commit error
	 */
	public synchronized static Msgboard addMessage(String content,
			int fromUserId, int toUserId, int inUserId) {
		Date date = new Date();
		Msgboard message = null;
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		if (content.length() > SNSConstants.MAX_MESSAGE_SIZE)
			content = content.substring(0, SNSConstants.MAX_MESSAGE_SIZE);
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			message = new Msgboard(fromUserId, toUserId, inUserId, content,
					date);
			if (fromUserId == toUserId)
				message.setChecked(true);
			else
				message.setChecked(false);
			mbDao.save(message);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return null;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return message;
	}

	/**
	 * 用户修改留言
	 * 
	 * @param content
	 * @param fromUserId
	 * @param userId
	 * @param messageId
	 * @return null if error
	 */
	public synchronized static Msgboard modifyMessage(String content,
			int fromUserId, int userId, int messageId) {
		Date date = new Date();
		Msgboard message = null;
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			if (mbDao.findById(messageId) == null) {
				HibernateSessionFactory.getSession().close();
				return null;
			}
			message = mbDao.findById(messageId);
			if (message.getMsgFromId() != fromUserId
					|| message.getMsgToId() != userId) {
				HibernateSessionFactory.getSession().close();
				return null;
			}
			if (content.length() > SNSConstants.MAX_MESSAGE_SIZE)
				content = content.substring(0, SNSConstants.MAX_MESSAGE_SIZE);
			message.setContent(content);
			message.setDate(date);
			mbDao.attachDirty(message);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return null;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return message;
	}

	/**
	 * 用户删除留言
	 * 
	 * @param userId
	 * @param messageId
	 * @return -2 not a message of this user, -1 message not exist, 0 commit
	 *         error, 1 commit OK
	 */
	public synchronized static int deleteMessage(int userId, int messageId) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			if (mbDao.findById(messageId) == null) {
				HibernateSessionFactory.getSession().close();
				return -1;
			}
			Msgboard message = mbDao.findById(messageId);
			if (message.getMsgInId() != userId
					|| message.getMsgFromId() != userId) {
				HibernateSessionFactory.getSession().close();
				return -3;
			}
			mbDao.delete(message);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return 0;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return 1;
	}

	/**
	 * 获取用户回复
	 * 
	 * @param userId
	 * @return null if there is no message found
	 */
	public synchronized static ArrayList<Msgboard> getMessageByToUserId(
			int userId) {
		ArrayList<Msgboard> result = new ArrayList<Msgboard>();
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			result = (ArrayList<Msgboard>) mbDao.findByMsgToId(userId);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return result;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		Collections.sort(result, new Comparator<Msgboard>() {

			@Override
			public int compare(Msgboard o1, Msgboard o2) {
				return o2.getDate().compareTo(o1.getDate());
			}

		});
		return result;
	}

	/**
	 * 获取用户留言板列表
	 * 
	 * @param userId
	 * @return null if there is no message found
	 */
	public synchronized static ArrayList<Msgboard> getMessageByInUserId(
			int userId) {
		ArrayList<Msgboard> result = new ArrayList<Msgboard>();
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			result = (ArrayList<Msgboard>) mbDao.findByMsgInId(userId);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return result;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		Collections.sort(result, new Comparator<Msgboard>() {
			@Override
			public int compare(Msgboard o1, Msgboard o2) {
				return o2.getDate().compareTo(o1.getDate());
			}

		});
		return result;
	}

	/**
	 * 获取一个用户对另一位用户的所有留言
	 * 
	 * @param fromUserId
	 * @param userId
	 * @return null if there is no message found
	 */
	public synchronized static ArrayList<Msgboard> getMessage(int fromUserId,
			int userId) {
		ArrayList<Msgboard> result = new ArrayList<Msgboard>();
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		ArrayList<Msgboard> tempResult = null;
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			tempResult = (ArrayList<Msgboard>) mbDao.findByMsgToId(userId);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return result;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		if (tempResult == null || tempResult.size() == 0)
			return result;
		for (int i = 0; i < tempResult.size(); i++)
			if (tempResult.get(i).getMsgFromId() == fromUserId)
				result.add(tempResult.get(i));
		Collections.sort(result, new Comparator<Msgboard>() {

			@Override
			public int compare(Msgboard o1, Msgboard o2) {
				return o2.getDate().compareTo(o1.getDate());
			}

		});
		return result;
	}

	/**
	 * 获取具体某一条留言详细内容
	 * 
	 * @param fromUserId
	 * @param userId
	 * @param messageId
	 * @return null if there is no message found
	 */
	public synchronized static Msgboard getMessage(int fromUserId, int userId,
			int messageId) {
		Msgboard result = null;
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO usDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			if (usDao.findById(messageId) == null) {
				HibernateSessionFactory.getSession().close();
				return null;
			}
			result = usDao.findById(messageId);
			if (result.getMsgFromId() != fromUserId
					|| result.getMsgToId() != userId) {
				HibernateSessionFactory.getSession().close();
				return null;
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return result;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return result;
	}

	/**
	 * 获取用户最新留言
	 * 
	 * @param userId
	 * @return null if there is no message at all
	 */
	public synchronized static Msgboard getLatestMessage(int userId) {
		Msgboard result = null;
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			ArrayList<Msgboard> messageList = (ArrayList<Msgboard>) mbDao
					.findByMsgToId(userId);
			if (messageList == null) {
				HibernateSessionFactory.getSession().close();
				return null;
			}
			Iterator<Msgboard> it = messageList.iterator();
			if (it.hasNext())
				result = it.next();
			else {
				HibernateSessionFactory.getSession().close();
				return null;
			}
			while (it.hasNext()) {
				Msgboard tempMessage = it.next();
				if (tempMessage.getDate().compareTo(result.getDate()) > 0)
					result = tempMessage;
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return result;
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return result;
	}

	public synchronized static ArrayList<Msgboard> findByUnchecked(int toUserId) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		return (ArrayList<Msgboard>) mbDao.findByUnchecked(toUserId);
	}

	public synchronized static void setChecked(int mailId, int toUserId) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IMsgboardDAO mbDao = factory.getMsgboardDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			Msgboard msg = mbDao.findById(mailId);
			if (msg.getMsgToId() == toUserId) {
				msg.setChecked(true);
				mbDao.attachDirty(msg);
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.getSession().close();
		}
	}
	
}
